<template>
  <div class="fc-style">
    <ElContainer class="fc-container">
      <ElMain class="fc-main">
        <ElContainer>
          <ElAside style="width: 250px" width="250px">
            <div class="components">
              <ComponentGroup
                title="基础控件"
                :fields="basicFields"
                :list="element.basicComponents"
                :isTables="isTables"
                :json="widgetForm"
              />
              <ComponentGroup
                title="快速控件"
                :fields="basicFields"
                :list="element.fastComponent"
                :isTables="isTables"
                :json="widgetForm"
                :pattern="pattern"
              />
              <ComponentGroup
                title="高级控件"
                :fields="advanceFields"
                :list="element.advanceComponents"
                :isTables="isTables"
                :json="widgetForm"
              />
              <ComponentGroup
                title="布局控件"
                :fields="layoutFields"
                :list="element.layoutComponents"
                :isTables="isTables"
                :json="widgetForm"
              />
            </div>
          </ElAside>
          <ElMain class="center-container">
            <CustomHeader
              v-bind="$props"
              @uploadJson="() => (uploadJsonVisible = true)"
              @generateJson="handleGenerateJson"
              @saveJson="handleSaveJson"
              @clearable="handleClearable"
              @generateCode="handleGenerateCode"
              @pcPattern="handlePcPattern"
              @phonePattern="handlePhonePattern"
              @automaticallyLanguageNum="handleAutomaticallyLanguageNum"
            >
              <slot name="header"></slot>
            </CustomHeader>
            <ElMain :class="{ 'widget-empty': widgetForm.display_area }">
              <XWidgetForm
                ref="widgetFormRef"
                v-model:widgetForm="widgetForm"
                v-model:widgetFormSelect="widgetFormSelect"
                :isTables="isTables"
              />
            </ElMain>
          </ElMain>
          <div style="width: 300px; position: relative" ref="container">
            <div style="width: 100%; height: 100%; overflow: hidden">
              <ElAside class="widget-config-container" style="width: 300px">
                <ElContainer style="display: flex; flex-direction: column">
                  <ElHeader stretch class="mike_header">
                    <div
                      class="config-tab"
                      :class="{ active: configTab === 'widget' }"
                      @click="configTab = 'widget'"
                    >
                      控件属性
                    </div>
                    <div
                      class="config-tab"
                      :class="{ active: configTab === 'expert' }"
                      @click="configTab = 'expert'"
                      v-if="workStationEv"
                    >
                      高级属性
                    </div>
                    <div
                      class="config-tab"
                      :class="{ active: configTab === 'validation' }"
                      @click="configTab = 'validation'"
                      v-if="workStationV"
                    >
                      验证规则
                    </div>
                    <div
                      class="config-tab"
                      :class="{ active: configTab === 'form' }"
                      @click="configTab = 'form'"
                    >
                      表属性
                    </div>
                    <div
                      class="config-tab"
                      v-if="pattern == 'phone'"
                      :class="{ active: configTab === 'phonePattern' }"
                      @click="configTab = 'phonePattern'"
                    >
                      导航栏
                    </div>
                  </ElHeader>
                  <ElMain class="config-content">
                    <WidgetConfig
                      v-show="configTab === 'widget'"
                      v-model:select="widgetFormSelect"
                      v-model:json="widgetForm"
                    />

                    <FormConfig
                      v-show="configTab === 'form'"
                      v-model:config="widgetForm.config"
                      v-model:json="widgetForm"
                      :pattern="pattern"
                    />
                    <FormExpert
                      v-show="configTab === 'expert'"
                      v-model:select="widgetFormSelect"
                      v-model:json="widgetForm"
                      v-model:dataUnit="dataUnit"
                    />
                    <FormValidation
                      v-show="configTab === 'validation'"
                      v-model:select="widgetFormSelect"
                    />
                    <phoneHeaderForm
                      v-show="configTab === 'phonePattern' && pattern == 'phone'"
                      v-model:phoneHeaderConfig="widgetForm.phoneHeaderConfig"
                      v-model:json="widgetForm"
                    />
                  </ElMain>
                </ElContainer>
              </ElAside>
            </div>
            <div class="select-right-arrow" @click="hanldeRightWidth">
              <span ref="selectArrow"></span>
            </div>
          </div>
        </ElContainer>
      </ElMain>

      <ElDialog v-model="uploadJsonVisible" title="导入JSON" :width="800">
        <ElAlert
          type="info"
          title="JSON格式如下，直接复制生成的json覆盖此处代码点击确定即可"
          style="margin-bottom: 10px"
        />
        <CodeEditor v-model:value="jsonEg" language="json" />
        <template #footer>
          <ElButton @click="() => (uploadJsonVisible = false)">取消</ElButton>
          <ElButton type="primary" @click="handleUploadJson">导入</ElButton>
        </template>
      </ElDialog>

      <!-- <ElDialog v-model="previewVisible" title="预览" :width="800">
        <GenerateForm ref="generateFormRef" v-if="previewVisible" :data="widgetForm" />
        <template #footer>
          <ElButton @click="handleReset">重置</ElButton>
          <ElButton type="primary" @click="handleGetData">获取数据</ElButton>
        </template>

        <ElDialog v-model="dataJsonVisible" title="获取数据" :width="800">
          <CodeEditor :value="dataJsonTemplate" language="json" readonly />

          <template #footer>
            <ElButton @click="() => (dataJsonVisible = false)">取消</ElButton>
            <ElButton type="primary" @click="handleCopyClick(dataJsonTemplate)">Copy</ElButton>
          </template>
        </ElDialog>
      </ElDialog> -->

      <ElDialog v-model="generateJsonVisible" title="生成JSON" :width="800">
        <CodeEditor :value="generateJsonTemplate" language="json" readonly />

        <template #footer>
          <ElButton @click="() => (generateJsonVisible = false)">取消</ElButton>
          <ElButton type="primary" @click="handleCopyClick(generateJsonTemplate)">Copy</ElButton>
        </template>
      </ElDialog>
      <ElDialog v-model="dataCodeVisible" title="生产代码" :width="800">
        <ElTabs type="card" v-model="codeLanguage" :tabBarStyle="{ margin: 0 }">
          <ElTabPane label="Vue Component" :name="codeType.Vue">
            <CodeEditor :value="dataCodeTemplate" language="html" readonly />
          </ElTabPane>
          <ElTabPane label="HTML" :name="codeType.Html">
            <CodeEditor :value="dataCodeTemplate" language="html" readonly />
          </ElTabPane>
        </ElTabs>

        <template #footer>
          <ElButton @click="() => (dataCodeVisible = false)">取消</ElButton>
          <ElButton type="primary" @click="handleCopyClick(dataCodeTemplate)">Copy</ElButton>
        </template>
      </ElDialog>
    </ElContainer>
  </div>
</template>

<script lang="ts">
  import { PropType } from 'vue';
  import type { Action } from 'element-plus';
  import { defaultsDeep, forEach, merge } from 'lodash-es';
  import CustomHeader from '@/pages/lowcodePower/views/lowCode/components/element/CustomHeader.vue';
  import XWidgetForm from '@/pages/lowcodePower/views/lowCode/components/element/WidgetForm.vue';
  import WidgetConfig from '@/pages/lowcodePower/views/lowCode/components/element/WidgetConfig.vue';
  import FormConfig from '@/pages/lowcodePower/views/lowCode/components/element/FormConfig.vue';
  import FormExpert from '@/pages/lowcodePower/views/lowCode/components/element/FormExpert.vue';
  import FormValidation from '@/pages/lowcodePower/views/lowCode/components/element/FormValidation.vue';
  import phoneHeaderForm from '@/pages/lowcodePower/views/lowCode/components/element/phoneHeaderForm.vue';
  import { CodeType, PlatformType } from '@/enums';
  import { element, jsondata } from '@/types';
  import { copy } from '@/utils';
  import generateCode from '@/utils/generateCode';
  import {
    WidgetFormType,
    basicComponents,
    advanceComponents,
    layoutComponents,
    rules,
    PanesList,
    ColumsList,
    FoldList,
  } from '@/types/element';
  interface elementName {
    element_control: string;
  }
  export default defineComponent({
    name: 'ElDesignForm',
    components: {
      CustomHeader,
      XWidgetForm,
      WidgetConfig,
      FormConfig,
      FormExpert,
      FormValidation,
      phoneHeaderForm,
    },
    props: {
      data: {
        type: Object,
        default: () => {},
      },
      elementJson: {
        type: Object,
        default: () => {},
      },
      generateJson: {
        type: Boolean,
        default: true,
      },
      saveJson: {
        type: Boolean,
        default: true,
      },
      uploadJson: {
        type: Boolean,
        default: true,
      },
      clearable: {
        type: Boolean,
        default: true,
      },
      pcPattern: {
        type: Boolean,
        default: true,
      },
      phonePattern: {
        type: Boolean,
        default: true,
      },
      pattern: {
        type: String,
        default: 'pc',
      },
      basicFields: {
        type: Array as PropType<Array<string>>,
        default: () => [
          'input',
          'password',
          'textarea',
          'number',
          'radio',
          'checkbox',
          'time',
          'date',
          'rate',
          'select',
          'switch',
          'slider',
          'text',
          'button',
          'images',
        ],
      },
      advanceFields: {
        type: Array as PropType<Array<string>>,
        default: () => [
          'uploadForm',
          'custom',
          'richtext',
          'cascader',
          'unit',
          'popText',
          'richtext',
          'timeLine',
          'steps',
          'processAdvice',
          'userChoice',
          'dynamicParameters',
          'filePreview',
          'input',
          'copyRow',
          'tips',
        ],
      },
      layoutFields: {
        type: Array as PropType<Array<string>>,
        default: () => ['tabs', 'grid', 'buttonArea', 'foldedPanel', 'divider', 'divLayout'],
      },
      isTables: {
        type: Boolean,
        default: false,
      },
    },
    emits: ['sendSavejson', 'sendTabsJson', 'sendPattern', 'getLanguaggeNum'],
    setup(sProps, ctx) {
      const state = reactive({
        element,
        widgetForm: JSON.parse(JSON.stringify(element.widgetForm)),
        codeType: CodeType,
        widgetFormSelect: undefined || (null as unknown as elementName),
        configTab: 'widget',
        uploadJsonVisible: false,
        dataCodeVisible: false,
        generateJsonVisible: false,
        codeLanguage: CodeType.Vue,
        generateJsonTemplate: JSON.stringify(element.widgetForm, null, 2),
        dataCodeTemplate: '',
        jsonEg: JSON.stringify(element.widgetForm, null, 2),
        workStationEv: true,
        workStationV: true,
        elementName: '',
        advanceFields: sProps.isTables
          ? ['uploadForm', 'custom', 'cascader', 'unit', 'popText', 'input', 'copyRow']
          : sProps.pattern == 'pc'
          ? [
              'uploadForm',
              'custom',
              'cascader',
              'unit',
              'popText',
              'richtext',
              'timeLine',
              'steps',
              'processAdvice',
              'userChoice',
              'dynamicParameters',
              'filePreview',
              'input',
              'tips',
            ]
          : [
              'uploadForm',
              'custom',
              'cascader',
              'unit',
              'popText',
              'richtext',
              'timeLine',
              'steps',
              'processAdvice',
              'userChoice',
              'dynamicParameters',
              'filePreview',
              'input',
              'tips',
              'inputScan',
            ],
        layoutFields: sProps.isTables
          ? ['buttonArea']
          : ['tabs', 'grid', 'foldedPanel', 'divider', 'divLayout'],
        dataUnit: sProps.data,
      });
      watch(
        () => state.widgetFormSelect?.element_control,
        (value: any) => {
          if (['richtext'].includes(value)) {
            state.workStationEv = false;
            state.configTab = 'widget';
          } else {
            state.workStationEv = true;
            state.configTab = state.configTab;
          }
          if (
            [
              'unit',
              'images',
              'tabs',
              'grid',
              'switch',
              'custom',
              'buttonArea',
              'foldedPanel',
              'divider',
              'richtext',
              'timeLine',
              'steps',
              'filePreview',
              'divLayout',
            ].includes(value)
          ) {
            state.workStationV = false;
            state.configTab = 'widget';
          } else {
            state.workStationV = true;
            state.configTab = state.configTab;
          }
        },
        {
          deep: true,
        },
      );
      const container = ref<HTMLElement | null>(null);
      const selectArrow = ref<HTMLElement | null>(null);
      const hanldeRightWidth = () => {
        let width = '300px';
        if (container!.value?.style.width == '0px') {
          if (selectArrow.value && container.value) {
            selectArrow.value.style.transform = 'translate(-50%, -50%) rotate(180deg)';
            container.value.style.width = width;
            selectArrow.value.style.left = '80%';
          }
        } else {
          if (selectArrow.value && container.value) {
            selectArrow.value.style.transform = 'translate(-50%, -50%) rotate(0deg)';
            container.value.style.width = '0';
            selectArrow.value.style.left = '50%';
          }
        }
      };

      const handleUploadJson = () => {
        let JsonData = JSON.parse(state.jsonEg);
        try {
          if (
            ['jstree-unit', 'jstree-region', 'jstree-query', 'jstree-wizard'].includes(
              sProps.data.dataId.icon,
            ) ||
            ['0', '1', '3'].includes(sProps.data.dataId.attributes?.unitType)
          ) {
            delete JsonData.config.pageType;
            // delete JsonData.config.pageHide;
            delete JsonData.config.listHeight;
            delete JsonData.config.listExport;
            delete JsonData.config.exportFileName;
            delete JsonData.config.pagEnum;
            delete JsonData.config.pageSizes;
            delete JsonData.config.pageh;
            // delete JsonData.config.locationon;
            // delete JsonData.config.locationback;
            // delete JsonData.config.listcontrol;
            delete JsonData.config.query;
            delete JsonData.config.fieldList;
            delete JsonData.config.listselection;
            delete JsonData.config.actionNo;
            delete JsonData.config.displayMode;
            delete JsonData.button_area;
            delete JsonData.config.listPrimaryField;
            delete JsonData.config.defaultSortField;
            delete JsonData.config.sortBy;
            delete JsonData.config.listUserCustomColumns;
            delete JsonData.config.listBottomTurnPage;
            if (!JsonData.config.displayMode) {
              JsonData.config.displayMode = '';
            }
          } else {
            if (JsonData.config.displayMode || JsonData.config.displayMode == '') {
              delete JsonData.config.displayMode;
            }
            if (!JsonData.button_area) {
              JsonData.button_area = [];
            }
            if (!JsonData.config.pageType) {
              JsonData.config.pageType = false;
              JsonData.config.listExport = false;
              JsonData.config.exportFileName = '';
              JsonData.config.fieldList = [];
            }
            if (!JsonData.config.listHeight) {
              JsonData.config.listHeight = false;
            }
            if (!JsonData.config.listExport) {
              JsonData.config.listExport = false;
              JsonData.config.exportFileName = '';
              JsonData.config.fieldList = [];
            }
            if (!JsonData.config.fieldList) {
              JsonData.config.fieldList = [];
            }
            if (!JsonData.config.pagEnum) {
              JsonData.config.pagEnum = 10;
            }
            if (!JsonData.config.pageSizes) {
              JsonData.config.pageSizes = '10, 20, 50, 100';
            }
            if (!JsonData.config.pageh) {
              JsonData.config.pageh = '';
            }
            if (!JsonData.config.query) {
              JsonData.config.query = '';
            }
            if (!JsonData.config.listselection) {
              JsonData.config.listselection = '0';
            }
            if (!JsonData.config.actionNo) {
              JsonData.config.actionNo = '';
            }
            if (!JsonData.config.defaultSortField) {
              JsonData.config.defaultSortField = '';
            }
            if (!JsonData.config.sortBy) {
              JsonData.config.sortBy = 'asc';
            }
            if (!JsonData.config.listUserCustomColumns) {
              JsonData.config.listUserCustomColumns = false;
            }
            if (!JsonData.config.listBottomTurnPage) {
              JsonData.config.listBottomTurnPage = false;
            }
          }
          setJson(JsonData);
          state.uploadJsonVisible = false;
          ElMessage.success('上传成功');
        } catch (error) {
          ElMessage.error('上传失败');
        }
      };

      const handleCopyClick = (text: string) => {
        copy(text);
        ElMessage.success('Copy成功');
      };

      const handleGenerateJson = () => {
        state.widgetForm.global_page = jsondata.value.global_page;
        state.generateJsonTemplate = JSON.stringify(state.widgetForm, null, 2);
        state.generateJsonVisible = true;
      };
      // (state.generateJsonTemplate = JSON.stringify(state.widgetForm, null, 2)) &&
      // (state.generateJsonVisible = true);

      const handleSaveJson = () => {
        ctx.emit('sendSavejson', JSON.stringify(state.widgetForm));
      };
      onBeforeUnmount(() => {
        ctx.emit('sendTabsJson', JSON.stringify(state.widgetForm));
      });

      const handleGenerateCode = () => {
        state.dataCodeVisible = true;
      };

      const handlePcPattern = (val: string) => {
        ElMessageBox.confirm('即将切换到PC模式，请确保当前数据已被保存，是否继续?', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          ctx.emit('sendPattern', val);
        });
      };

      const handlePhonePattern = (val: string) => {
        ElMessageBox.confirm('即将切换到移动端模式，请确保当前数据已被保存，是否继续?', '提示', {
          confirmButtonText: '继续',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          ctx.emit('sendPattern', val);
        });
      };

      const handleAutomaticallyLanguageNum = () => {
        ctx.emit('getLanguaggeNum', JSON.stringify(state.widgetForm));
      };

      watchEffect(() => {
        if (state.dataCodeVisible) {
          state.dataCodeTemplate = generateCode(
            state.widgetForm,
            state.codeLanguage,
            PlatformType.Element,
          )!;
        }
      });
      const handleListInsert = (list: any) => {
        const newList: any[] = [];
        if (list) {
          list.forEach((item) => {
            const contrastBasis = basicComponents.filter((items) => {
              return items.element_control === item.element_control;
            });
            const contrastSenior = advanceComponents.filter((items) => {
              return items.element_control === item.element_control;
            });
            const contrastLayout = layoutComponents.filter((items) => {
              return items.element_control === item.element_control;
            });
            if (!item.list || !item.panel || !item.columns || !item.panes) {
              if (contrastBasis.length) {
                item = Object.assign({}, contrastBasis[0], item);
              } else if (contrastSenior.length) {
                item = Object.assign({}, contrastSenior[0], item);
              } else if (contrastLayout.length) {
                if (item.columns) {
                  item.columns = item.columns.map((items: any) =>
                    Object.assign({}, ColumsList.value[0], items),
                  );
                }
                if (item.panes) {
                  item.panes = item.panes.map((items: any) =>
                    Object.assign({}, PanesList.value[0], items),
                  );
                }
                if (item.panel) {
                  item.panel = item.panel.map((items: any) =>
                    Object.assign({}, FoldList.value[0], items),
                  );
                }
                if (item.list) {
                  item.list = item.list.map((items: any) =>
                    Object.assign({}, contrastLayout[0], items),
                  );
                }
                if (!item.list || !item.panel || !item.columns || !item.panes) {
                  item = Object.assign({}, contrastLayout[0], item);
                }
              }
              newList.push(item);
            } else {
              if (item.columns) {
                item.columns = item.columns.map((col: any) => ({
                  ...col,
                  list: handleListInsert(col),
                }));
              }
              if (item.panes) {
                item.panes = item.panes.map((col: any) => ({
                  ...col,
                  list: handleListInsert(col),
                }));
              }
              if (item.panel) {
                item.panel = item.panel.map((col: any) => ({
                  ...col,
                  list: handleListInsert(col),
                }));
              }
              newList.push(item);
            }
          });
        }
        return newList;
      };
      watch(
        () => sProps.data.dataId,
        async (value) => {
          if (value.id) {
            if (
              ['jstree-unit', 'jstree-region', 'jstree-query', 'jstree-wizard'].includes(
                value.icon,
              ) ||
              ['0', '1', '3'].includes(value.attributes?.unitType)
            ) {
              delete state.widgetForm.button_area;
              state.jsonEg = JSON.stringify(state.widgetForm, null, 2);
              state.widgetForm.display_area = jsondata.value.display_area;
              state.widgetForm.hidden_area = jsondata.value.hidden_area;
              state.widgetForm.trash_area = jsondata.value.trash_area;
              state.widgetForm.config = jsondata.value.config;
              state.widgetForm.phoneHeaderConfig = jsondata.value.phoneHeaderConfig;
            } else {
              state.jsonEg = JSON.stringify(state.widgetForm, null, 2);
              state.widgetForm.display_area = jsondata.value.display_area;
              state.widgetForm.hidden_area = jsondata.value.hidden_area;
              state.widgetForm.trash_area = jsondata.value.trash_area;
              state.widgetForm.button_area = jsondata.value.button_area ?? [];
              state.widgetForm.config = jsondata.value.config;
              state.widgetForm.phoneHeaderConfig = jsondata.value.phoneHeaderConfig;
            }
            for (let i = 0; i < state.widgetForm.display_area.length; i++) {
              const contrastBasis = basicComponents.filter((item) => {
                return item.element_control === state.widgetForm.display_area[i].element_control;
              });
              const contrastSenior = advanceComponents.filter((item) => {
                return item.element_control === state.widgetForm.display_area[i].element_control;
              });
              const contrastLayout = layoutComponents.filter((item) => {
                return item.element_control === state.widgetForm.display_area[i].element_control;
              });
              if (
                state.widgetForm.display_area[i].rules &&
                JSON.stringify(state.widgetForm.display_area[i].rules) != '{}' &&
                state.widgetForm.display_area[i].rules.trigger
              ) {
                state.widgetForm.display_area[i].rules = Object.assign(
                  {},
                  rules,
                  state.widgetForm.display_area[i].rules,
                );
              } else if (
                state.widgetForm.display_area[i].columns ||
                state.widgetForm.display_area[i].panes ||
                state.widgetForm.display_area[i].list ||
                state.widgetForm.display_area[i].panel
              ) {
                forEach(state.widgetForm.display_area[i].columns, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.display_area[i].panes, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.display_area[i].list, (item: any) => {
                  if (item.rules && JSON.stringify(item.rules) != '{}' && item.rules.trigger) {
                    item.rules = Object.assign({}, rules, item.rules);
                  }
                  return;
                });
                forEach(state.widgetForm.display_area[i].panel, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
              }
              if (contrastBasis.length) {
                state.widgetForm.display_area[i] = Object.assign(
                  {},
                  contrastBasis[0],
                  state.widgetForm.display_area[i],
                );
              } else if (contrastSenior.length) {
                state.widgetForm.display_area[i] = Object.assign(
                  {},
                  contrastSenior[0],
                  state.widgetForm.display_area[i],
                );
              } else if (contrastLayout.length) {
                if (state.widgetForm.display_area[i].columns) {
                  state.widgetForm.display_area[i].columns = state.widgetForm.display_area[
                    i
                  ].columns.map((item: any) => Object.assign({}, ColumsList.value[0], item));
                  forEach(state.widgetForm.display_area[i].columns, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.display_area[i].panes) {
                  state.widgetForm.display_area[i].panes = state.widgetForm.display_area[
                    i
                  ].panes.map((item: any) => Object.assign({}, PanesList.value[0], item));

                  forEach(state.widgetForm.display_area[i].panes, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.display_area[i].panel) {
                  state.widgetForm.display_area[i].panel = state.widgetForm.display_area[
                    i
                  ].panel.map((item: any) => Object.assign({}, FoldList.value[0], item));
                  forEach(state.widgetForm.display_area[i].panel, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.display_area[i].list) {
                  state.widgetForm.display_area[i].list = handleListInsert(
                    state.widgetForm.display_area[i].list,
                  );
                }

                state.widgetForm.display_area[i] = Object.assign(
                  {},
                  contrastLayout[0],
                  state.widgetForm.display_area[i],
                );
              }
              Object.keys(state.widgetForm.display_area[i]).reduce((acc, key) => {
                if (
                  state.widgetForm.display_area[i][key] === state.widgetForm.display_area[i][key]
                ) {
                  acc[key] = state.widgetForm.display_area[i][key];
                }
                return acc;
              }, {});
            }
            for (let i = 0; i < state.widgetForm.hidden_area.length; i++) {
              const contrastBasis = basicComponents.filter((item) => {
                return item.element_control === state.widgetForm.hidden_area[i].element_control;
              });
              const contrastSenior = advanceComponents.filter((item) => {
                return item.element_control === state.widgetForm.hidden_area[i].element_control;
              });
              const contrastLayout = layoutComponents.filter((item) => {
                return item.element_control === state.widgetForm.hidden_area[i].element_control;
              });
              if (
                state.widgetForm.hidden_area[i].rules &&
                JSON.stringify(state.widgetForm.hidden_area[i].rules) != '{}' &&
                state.widgetForm.hidden_area[i].rules.trigger
              ) {
                state.widgetForm.hidden_area[i].rules = Object.assign(
                  {},
                  rules,
                  state.widgetForm.hidden_area[i].rules,
                );
              } else if (
                state.widgetForm.hidden_area[i].columns ||
                state.widgetForm.hidden_area[i].panes ||
                state.widgetForm.hidden_area[i].list ||
                state.widgetForm.hidden_area[i].panel
              ) {
                forEach(state.widgetForm.hidden_area[i].columns, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.hidden_area[i].panes, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.hidden_area[i].list, (item: any) => {
                  if (item.rules && JSON.stringify(item.rules) != '{}' && item.rules.trigger) {
                    item.rules = Object.assign({}, rules, item.rules);
                  }
                  return;
                });
                forEach(state.widgetForm.hidden_area[i].panel, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
              }
              if (contrastBasis.length) {
                state.widgetForm.hidden_area[i] = Object.assign(
                  {},
                  contrastBasis[0],
                  state.widgetForm.hidden_area[i],
                );
              } else if (contrastSenior.length) {
                state.widgetForm.hidden_area[i] = Object.assign(
                  {},
                  contrastSenior[0],
                  state.widgetForm.hidden_area[i],
                );
              } else if (contrastLayout.length) {
                if (state.widgetForm.hidden_area[i].columns) {
                  state.widgetForm.hidden_area[i].columns = state.widgetForm.hidden_area[
                    i
                  ].columns.map((item: any) => Object.assign({}, ColumsList.value[0], item));
                  forEach(state.widgetForm.hidden_area[i].columns, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.hidden_area[i].panes) {
                  state.widgetForm.hidden_area[i].panes = state.widgetForm.hidden_area[i].panes.map(
                    (item: any) => Object.assign({}, PanesList.value[0], item),
                  );
                  forEach(state.widgetForm.hidden_area[i].panes, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.hidden_area[i].panel) {
                  state.widgetForm.hidden_area[i].panel = state.widgetForm.hidden_area[i].panel.map(
                    (item: any) => Object.assign({}, FoldList.value[0], item),
                  );
                  forEach(state.widgetForm.hidden_area[i].panel, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.hidden_area[i].list) {
                  state.widgetForm.hidden_area[i].list = handleListInsert(
                    state.widgetForm.hidden_area[i].list,
                  );
                }
                state.widgetForm.hidden_area[i] = Object.assign(
                  {},
                  contrastLayout[0],
                  state.widgetForm.hidden_area[i],
                );
              }
              Object.keys(state.widgetForm.hidden_area[i]).reduce((acc, key) => {
                if (state.widgetForm.hidden_area[i][key] === state.widgetForm.hidden_area[i][key]) {
                  acc[key] = state.widgetForm.hidden_area[i][key];
                }
                return acc;
              }, {});
            }
            for (let i = 0; i < state.widgetForm.trash_area.length; i++) {
              const contrastBasis = basicComponents.filter((item) => {
                return item.element_control === state.widgetForm.trash_area[i].element_control;
              });
              const contrastSenior = basicComponents.filter((item) => {
                return item.element_control === state.widgetForm.trash_area[i].element_control;
              });
              const contrastLayout = layoutComponents.filter((item) => {
                return item.element_control === state.widgetForm.trash_area[i].element_control;
              });
              if (
                state.widgetForm.trash_area[i].rules &&
                JSON.stringify(state.widgetForm.trash_area[i].rules) != '{}' &&
                state.widgetForm.trash_area[i].rules.trigger
              ) {
                state.widgetForm.trash_area[i].rules = Object.assign(
                  {},
                  rules,
                  state.widgetForm.trash_area[i].rules,
                );
              } else if (
                state.widgetForm.trash_area[i].columns ||
                state.widgetForm.trash_area[i].panes ||
                state.widgetForm.trash_area[i].list ||
                state.widgetForm.trash_area[i].panel
              ) {
                forEach(state.widgetForm.trash_area[i].columns, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.trash_area[i].panes, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.trash_area[i].list, (item: any) => {
                  if (item.rules && JSON.stringify(item.rules) != '{}' && item.rules.trigger) {
                    item.rules = Object.assign({}, rules, item.rules);
                  }
                  return;
                });
                forEach(state.widgetForm.trash_area[i].panel, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
              }
              if (contrastBasis.length) {
                state.widgetForm.trash_area[i] = Object.assign(
                  {},
                  contrastBasis[0],
                  state.widgetForm.trash_area[i],
                );
              } else if (contrastSenior.length) {
                state.widgetForm.trash_area[i] = Object.assign(
                  {},
                  contrastSenior[0],
                  state.widgetForm.trash_area[i],
                );
              } else if (contrastLayout.length) {
                if (state.widgetForm.trash_area[i].columns) {
                  state.widgetForm.trash_area[i].columns = state.widgetForm.trash_area[
                    i
                  ].columns.map((item: any) => Object.assign({}, ColumsList.value[0], item));
                  forEach(state.widgetForm.trash_area[i].columns, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.trash_area[i].panes) {
                  state.widgetForm.trash_area[i].panes = state.widgetForm.trash_area[i].panes.map(
                    (item: any) => Object.assign({}, PanesList.value[0], item),
                  );
                  forEach(state.widgetForm.trash_area[i].panes, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.trash_area[i].panel) {
                  state.widgetForm.trash_area[i].panel = state.widgetForm.trash_area[i].panel.map(
                    (item: any) => Object.assign({}, FoldList.value[0], item),
                  );
                  forEach(state.widgetForm.trash_area[i].panel, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.trash_area[i].list) {
                  state.widgetForm.trash_area[i].list = handleListInsert(
                    state.widgetForm.trash_area[i].list,
                  );
                }
                state.widgetForm.trash_area[i] = Object.assign(
                  {},
                  contrastLayout[0],
                  state.widgetForm.trash_area[i],
                );
              }
              Object.keys(state.widgetForm.trash_area[i]).reduce((acc, key) => {
                if (state.widgetForm.trash_area[i][key] === state.widgetForm.trash_area[i][key]) {
                  acc[key] = state.widgetForm.trash_area[i][key];
                }
                return acc;
              }, {});
            }
            for (
              let i = 0;
              i < state.widgetForm.button_area && state.widgetForm.button_area.length;
              i++
            ) {
              const contrastBasis = basicComponents.filter((item) => {
                return item.element_control === state.widgetForm.button_area[i].element_control;
              });
              const contrastSenior = advanceComponents.filter((item) => {
                return item.element_control === state.widgetForm.button_area[i].element_control;
              });
              const contrastLayout = layoutComponents.filter((item) => {
                return item.element_control === state.widgetForm.button_area[i].element_control;
              });
              if (
                state.widgetForm.button_area[i].rules &&
                JSON.stringify(state.widgetForm.button_area[i].rules) != '{}' &&
                state.widgetForm.button_area[i].rules.trigger
              ) {
                state.widgetForm.button_area[i].rules = Object.assign(
                  {},
                  rules,
                  state.widgetForm.button_area[i].rules,
                );
              } else if (
                state.widgetForm.button_area[i].columns ||
                state.widgetForm.button_area[i].panes ||
                state.widgetForm.button_area[i].list ||
                state.widgetForm.button_area[i].panel
              ) {
                forEach(state.widgetForm.button_area[i].columns, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.button_area[i].panes, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
                forEach(state.widgetForm.button_area[i].list, (item: any) => {
                  if (item.rules && JSON.stringify(item.rules) != '{}' && item.rules.trigger) {
                    item.rules = Object.assign({}, rules, item.rules);
                  }
                  return;
                });
                forEach(state.widgetForm.button_area[i].panel, (item: any) => {
                  forEach(item.list, (list: any) => {
                    if (list.rules && JSON.stringify(list.rules) != '{}' && list.rules.trigger) {
                      list.rules = Object.assign({}, rules, list.rules);
                    }
                  });
                  return;
                });
              }
              if (contrastBasis.length) {
                state.widgetForm.button_area[i] = Object.assign(
                  {},
                  contrastBasis[0],
                  state.widgetForm.button_area[i],
                );
              } else if (contrastSenior.length) {
                state.widgetForm.button_area[i] = Object.assign(
                  {},
                  contrastSenior[0],
                  state.widgetForm.button_area[i],
                );
              } else if (contrastLayout.length) {
                if (state.widgetForm.button_area[i].columns) {
                  state.widgetForm.button_area[i].columns = state.widgetForm.button_area[
                    i
                  ].columns.map((item: any) => Object.assign({}, ColumsList.value[0], item));
                  forEach(state.widgetForm.button_area[i].columns, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.button_area[i].panes) {
                  state.widgetForm.button_area[i].panes = state.widgetForm.button_area[i].panes.map(
                    (item: any) => Object.assign({}, PanesList.value[0], item),
                  );
                  forEach(state.widgetForm.button_area[i].panes, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.button_area[i].panel) {
                  state.widgetForm.button_area[i].panel = state.widgetForm.button_area[i].panel.map(
                    (item: any) => Object.assign({}, FoldList.value[0], item),
                  );
                  forEach(state.widgetForm.button_area[i].panel, (item: any) => {
                    if (item.list) {
                      item.list = handleListInsert(item.list);
                    }
                    return;
                  });
                }
                if (state.widgetForm.button_area[i].list) {
                  state.widgetForm.button_area[i].list = handleListInsert(
                    state.widgetForm.button_area[i].list,
                  );
                }
                state.widgetForm.button_area[i] = Object.assign(
                  {},
                  contrastLayout[0],
                  state.widgetForm.button_area[i],
                );
              }
              Object.keys(state.widgetForm.button_area[i]).reduce((acc, key) => {
                if (state.widgetForm.button_area[i][key] === state.widgetForm.button_area[i][key]) {
                  acc[key] = state.widgetForm.button_area[i][key];
                }
                return acc;
              }, {});
            }
            // state.widgetForm.config = Object.assign(jsondata.value.config, state.widgetForm.config);
            // Object.keys(state.widgetForm.config).reduce((acc, key) => {
            //   if (state.widgetForm.config[key] === state.widgetForm.config[key]) {
            //     acc[key] = state.widgetForm.config[key];
            //   }
            //   return acc;
            // }, {});
          }
        },
        {
          deep: true,
          immediate: true,
        },
      );

      const handleClearable = () => {
        ElMessageBox.alert('是否需要全部清空！', '提示', {
          closeOnPressEscape: true,
          showCancelButton: true,
          cancelButtonText: '取消',
          confirmButtonText: '确定',
          callback: (action: Action) => {
            if (action === 'confirm') {
              let Json = JSON.parse(JSON.stringify(element.widgetForm));
              if (
                ['jstree-unit', 'jstree-region', 'jstree-query', 'jstree-wizard'].includes(
                  sProps.data.dataId.icon,
                ) ||
                ['0', '1', '3'].includes(sProps.data.dataId.attributes?.unitType)
              ) {
                delete Json.button_area;
              } else {
                if (state.widgetForm.button_area.length && state.widgetForm.button_area) {
                  state.widgetForm.button_area = [];
                  jsondata.value.button_area = [];
                }
              }
              state.widgetForm.display_area = [];
              state.widgetForm.hidden_area = [];
              state.widgetForm.trash_area = [];
              state.widgetForm.global_page = {};

              jsondata.value.display_area = [];
              jsondata.value.hidden_area = [];
              jsondata.value.trash_area = [];
              jsondata.value.global_page = {};
              defaultsDeep(state.widgetForm, Json);
              state.widgetFormSelect = undefined || (null as unknown as elementName);
              ElMessage.success('清除成功！');
            }
          },
        });
      };

      const getJson = () => state.widgetForm;

      const setJson = (json: WidgetFormType) => {
        if (
          ['jstree-unit', 'jstree-region', 'jstree-query', 'jstree-wizard'].includes(
            sProps.data.dataId.icon,
          ) ||
          ['0', '1', '3'].includes(sProps.data.dataId.attributes?.unitType)
        ) {
          delete state.widgetForm.button_area;
          delete jsondata.value.button_area;
        } else {
          state.widgetForm.button_area = [];
          jsondata.value.button_area = [];
          if (json.button_area.length) {
            state.widgetFormSelect = json.button_area[0];
            jsondata.value.button_area = json.button_area[0];
          }
        }
        state.widgetForm.display_area = [];
        state.widgetForm.hidden_area = [];
        state.widgetForm.trash_area = [];
        state.widgetForm.global_page = {};
        merge(state.widgetForm, json);
        if (json.display_area.length) {
          state.widgetFormSelect = json.display_area[0];
        }
        if (json.hidden_area.length) {
          state.widgetFormSelect = json.hidden_area[0];
        }
        if (json.trash_area.length) {
          state.widgetFormSelect = json.trash_area[0];
        }
        if (json.global_page) {
          state.widgetFormSelect = json.global_page;
        }
        jsondata.value = json;
        // state.widgetForm.display_area = [];
        // defaultsDeep(state.widgetForm, json);
        // if (json.display_area.length) {
        //   state.widgetFormSelect = json.display_area[0];
        // }
      };

      const getTemplate = (codeType: CodeType) =>
        generateCode(state.widgetForm, codeType, PlatformType.Element);

      const clear = () => handleClearable();

      return {
        ...toRefs(state),
        handleUploadJson,
        handleCopyClick,
        handleGenerateJson,
        getTemplate,
        handleSaveJson,
        handleGenerateCode,
        handleClearable,
        getJson,
        setJson,
        clear,
        hanldeRightWidth,
        container,
        selectArrow,
        handlePcPattern,
        handlePhonePattern,
        handleAutomaticallyLanguageNum,
      };
    },
  });
</script>

<style lang="scss" scoped>
  :deep(.mike_header) {
    display: flex;
    align-items: center;
  }
  .select-right-arrow {
    position: absolute;
    width: 16px;
    height: 50px;
    top: 50%;
    left: -16px;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    background-color: transparent;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    z-index: 10;
    cursor: pointer;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    justify-content: center;
    span {
      display: block;
      position: absolute;
      width: 0;
      height: 0;
      border-width: 5px;
      border-color: transparent;
      border-right-color: var(--el-menu-border-color);
      border-style: solid;
      left: 80%;
      top: 50%;
      -webkit-mask-size: 100% 100%;
      mask-size: 100% 100%;
      -webkit-mask-repeat: no-repeat;
      mask-repeat: no-repeat;
      -webkit-transform: translate(-50%, -50%) rotate(180deg);
      transform: translate(-50%, -50%) rotate(180deg);
    }
  }
  .select-right-arrow::before {
    content: '';
    position: absolute;
    border-radius: 0 10px 10px 0;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border-left: 0;
    border-color: var(--el-menu-border-color);
    border-style: solid;
    top: 0;
    right: 0;
    bottom: 0;
    left: 1px;
    background: var(--el-fill-color-blank);
    z-index: -1;
    -webkit-transform: perspective(50px) rotateY(140deg);
    transform: perspective(50px) rotateY(140deg);
    -webkit-transition: all 0.15s;
    transition: all 0.15s;
  }
</style>
